package net.jueb.protobufs2.client;

import net.jueb.protobufs2.pojo.MessageProto.Login;
import net.jueb.protobufs2.pojo.MessageProto.Message;
import net.jueb.protobufs2.pojo.MessageProto.MessageType;
import net.jueb.protobufs2.pojo.MessageProto.Regist;
import net.jueb.protobufs2.pojo.MessageProto.Request;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

public class ProtoClientHandler extends ChannelHandlerAdapter {

	public Message getMessage(MessageType type) {
		Message.Builder messageBuilder = Message.newBuilder();// 设置消息主体
		messageBuilder.setMsgId(Thread.currentThread().hashCode());// 设置消息ID
		Request.Builder requestBuilder = Request.newBuilder();// 请求消息集合
		Login login = Login.newBuilder().setUsername("admin")
				.setPassword("123456").build();
		Regist regist = Regist.newBuilder().setUsername("admin")
				.setPassword("123456").setMail("xxx@qq.com").build();
		switch (type.getNumber()) {
		case MessageType.Type_Regist_VALUE:
			// 装入登录消息
			messageBuilder.setMsgType(MessageType.Type_Regist);
			requestBuilder.setRegist(regist);
			break;
		case MessageType.Type_Login_VALUE:
			// 装入注册消息
			messageBuilder.setMsgType(MessageType.Type_Login);
			requestBuilder.setLogin(login);
			break;
		default:
			break;
		}
		// 装入消息集合到消息主体
		messageBuilder.setRequest(requestBuilder.build());
		return messageBuilder.build();
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		// 发出注册请求
		ctx.writeAndFlush(getMessage(MessageType.Type_Regist));
		// 发出登录请求
		ctx.writeAndFlush(getMessage(MessageType.Type_Login));
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {
		Message m = (Message) msg;
		if (m == null) {
			return;
		}
		switch (m.getMsgType().getNumber()) {
		case MessageType.Type_Result_VALUE:
			System.out.println("收到回复:" + m.getResponse().getResult());
			break;
		default:
			System.out.println("收到回复:" + m);
			break;
		}
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
		cause.printStackTrace();
		ctx.close();
	}
}
